import { get } from '@/utils/request'
import { getApiBaseUrl } from '@/config'

/**
 * AI 聊天请求参数
 */
export interface ChatRequest {
  message: string
  model?: string
  temperature?: number
  sessionId?: string
}

/**
 * AI 聊天响应
 */
export interface ChatResponse {
  Message: string
  SessionId: string
  IsComplete: boolean
  Model?: string
}

/**
 * AI 相关服务类
 * 统一管理所有 AI 相关的 API 请求
 */
class AIService {
  /**
   * 流式聊天（SSE）
   * @param request 聊天请求参数
   * @param signal AbortSignal 用于取消请求
   * @returns ReadableStreamDefaultReader 流式响应
   */
  async streamChat(
    request: ChatRequest,
    signal?: AbortSignal
  ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
    const baseUrl = getApiBaseUrl()
    const path = '/AI/chat/stream'
    const apiUrl = `${baseUrl}${path}`
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
      signal
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }

    return reader
  }

  /**
   * 获取可用的模型列表
   * @returns Promise 模型列表
   */
  async getAvailableModels(): Promise<string[]> {
    const result = await get<string[]>('/AI/models')
    return result.data
  }

  /**
   * 健康检查
   * @returns Promise 健康状态
   */
  async healthCheck(): Promise<any> {
    const result = await get('/AI/health')
    return result.data
  }

  /**
   * 解析 SSE 数据流
   * @param reader ReadableStreamDefaultReader
   * @param onMessage 接收到消息时的回调
   * @param onComplete 完成时的回调
   * @param onError 错误时的回调
   */
  async parseSSEStream(
    reader: ReadableStreamDefaultReader<Uint8Array>,
    onMessage: (response: ChatResponse) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    const decoder = new TextDecoder()

    try {
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) {
          onComplete()
          break
        }

        const chunk = decoder.decode(value, { stream: true })
        const lines = chunk.split('\n')

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonStr = line.substring(6).trim()
              
              if (jsonStr) {
                const data: ChatResponse = JSON.parse(jsonStr)
                onMessage(data)
                
                if (data.IsComplete) {
                  onComplete()
                }
              }
            } catch (e) {
              onError(e)
            }
          }
        }
      }
    } catch (error) {
      onError(error)
    }
  }
}

// 导出单例实例
const aiServiceInstance = new AIService()
export default aiServiceInstance
